﻿using System;
using System.Web.Mvc;
using Kratos.Framework.ContentManagement.Models.SystemRights;
using Kratos.Framework.ContentManagement.ViewModels;
using Kratos.Framework.Filters;
using Kratos.Framework.Modules.Core.Controllers;
using Kratos.Framework.Modules.Core.Services;

namespace Kratos.Modules.Admin.Controllers
{
    public class MenuController : KratosController
    {
        private readonly IMenuPermissionService _menuSrv;

        public MenuController(IMenuPermissionService menuSrv)
        {
            _menuSrv = menuSrv;
        }

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取指定父菜单的子菜单
        /// </summary>
        public ActionResult GetMenuGrid(int? id)
        {
            id = id ?? -1;
            if (id == -1)
            {
                var roots = _menuSrv.GetMenusByLevel(1);
                return KratosJson(roots);
            }
            else
            {
                var roots = _menuSrv.GetMenu(id.Value);
                return KratosJson(roots);
            }
        }

        /// <summary>
        /// 获取指定id的菜单
        /// </summary>
        public ActionResult GetMenuById(int id)
        {
            var model = _menuSrv.GetMenuById(id);

            return KratosJson(model);
        }

        [UnitOfWork]
        public ActionResult AddMenu(MenuPermission m)
        {
            m.CreateTime = DateTime.Now;
            _menuSrv.Save(m);
            var extResult = new ExtResult { Success = true, Msg = "添加成功", Id = m.Id };

            return KratosJson(extResult);
        }

        [UnitOfWork]
        public ActionResult EditMenu(MenuPermission m)
        {
            _menuSrv.Update(m);
            var extResult = new ExtResult { Success = true, Msg = "修改成功" };

            return KratosJson(extResult);
        }

        [UnitOfWork]
        public ActionResult DeleteMenu(int id)
        {
            var model = _menuSrv.GetMenuById(id);
            _menuSrv.Delete(model);
            var extResult = new ExtResult { Success = true, Msg = "删除成功" };

            return KratosJson(extResult);
        }
    }
}
